
// Open MoneySpinner Suite v1
// An open source business management software system written in Java and MySQL
// Recommended IDE is NetBeans IDE 7.0.1
// Support Web Site: http://www.milliscript.com
//
// Copyright (C) 2014, Abiodun Aremu, Ibadan/NIGERIA.
// Open MoneySpinner Suite is distributed under the terms of the Apache License version 2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package openmoneyspinnersuite;

/**
 *
 * @author Abiodun Aremu
 */
import javax.swing.*;

final class EditMerchantQuery extends javax.swing.JInternalFrame {

    Object[][] tableObject=new Object[][]{};
    Systems systems=new Systems();
    java.sql.PreparedStatement statement;
    Thread processThread=new Thread();
    Thread titleThread=new Thread();
    String[] attributeList=new String[]{};
    int updateType=0;
    /** Creates new form ViewCredit */
    EditMerchantQuery() {
        initComponents();
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            tableObject,
            new String [] {
                "Profile Attribute", "Merchant Name"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, true
            };

            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Boolean.class
            };
            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        /* Execute thread */
        processThread=new Thread(new Runnable() {
            public void run() {
            disableControls();
            reset();
            }
        });
        titleThread=new Thread(new Runnable() {
            public void run() {
                while(processThread.isAlive())setProcessingTitle(titleThread);
                enableControls();
                System.out.println("viewItemThread stopped runing.");
            }
        });
        processThread.start();
        titleThread.start();
        
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jRefreshButton = new javax.swing.JButton();
        jCancelButton = new javax.swing.JButton();
        jUpdateButton = new javax.swing.JButton();
        jComboBox1 = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jCheckBox1 = new javax.swing.JCheckBox();
        jCheckBox2 = new javax.swing.JCheckBox();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(openmoneyspinnersuite.OpenMS_Finance_App.class).getContext().getResourceMap(EditMerchantQuery.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setToolTipText(resourceMap.getString("Form.toolTipText")); // NOI18N
        setFrameIcon(resourceMap.getIcon("Form.frameIcon")); // NOI18N
        setName("Form"); // NOI18N
        setVisible(true);

        jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null}
            },
            new String [] {
                "Profile Attribute", "Merchant Name"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Boolean.class
            };
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setName("jTable1"); // NOI18N
        jTable1.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getColumn(0).setPreferredWidth(10);
        jTable1.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("jTable1.columnModel.title0")); // NOI18N
        jTable1.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("jTable1.columnModel.title4")); // NOI18N

        jRefreshButton.setFont(resourceMap.getFont("jRefreshButton.font")); // NOI18N
        jRefreshButton.setIcon(resourceMap.getIcon("jRefreshButton.icon")); // NOI18N
        jRefreshButton.setText(resourceMap.getString("jRefreshButton.text")); // NOI18N
        jRefreshButton.setName("jRefreshButton"); // NOI18N
        jRefreshButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRefreshButtonActionPerformed(evt);
            }
        });

        jCancelButton.setFont(resourceMap.getFont("jCancelButton.font")); // NOI18N
        jCancelButton.setIcon(resourceMap.getIcon("jCancelButton.icon")); // NOI18N
        jCancelButton.setText(resourceMap.getString("jCancelButton.text")); // NOI18N
        jCancelButton.setName("jCancelButton"); // NOI18N
        jCancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCancelButtonActionPerformed(evt);
            }
        });

        jUpdateButton.setIcon(resourceMap.getIcon("jUpdateButton.icon")); // NOI18N
        jUpdateButton.setText(resourceMap.getString("jUpdateButton.text")); // NOI18N
        jUpdateButton.setName("jUpdateButton"); // NOI18N
        jUpdateButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jUpdateButtonActionPerformed(evt);
            }
        });

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "-- Select --", "Item 2", "Item 3", "Item 4" }));
        jComboBox1.setName("jComboBox1"); // NOI18N
        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jCheckBox1.setText(resourceMap.getString("jCheckBox1.text")); // NOI18N
        jCheckBox1.setName("jCheckBox1"); // NOI18N

        jCheckBox2.setText(resourceMap.getString("jCheckBox2.text")); // NOI18N
        jCheckBox2.setName("jCheckBox2"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jUpdateButton)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jRefreshButton)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jCancelButton))
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jLabel1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jCheckBox1)
                            .addGap(10, 10, 10)
                            .addComponent(jCheckBox2))
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 378, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 25, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jCheckBox1)
                    .addComponent(jCheckBox2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jCancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jRefreshButton, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jUpdateButton, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jRefreshButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRefreshButtonActionPerformed
  
        if(jComboBox1.getSelectedItem().toString().equalsIgnoreCase("-- Select --"))
        {
            reset();
        }    
        else{
            /* Execute thread */
            processThread=new Thread(new Runnable() {
                public void run() {
                disableControls();
                refreshTable();
                }
            });
            titleThread=new Thread(new Runnable() {
                public void run() {
                    while(processThread.isAlive())setProcessingTitle(titleThread);
                    enableControls();
                    System.out.println("viewItemThread stopped runing.");
                }
            });
            processThread.start();
            titleThread.start();
        }
    }//GEN-LAST:event_jRefreshButtonActionPerformed

    private void jCancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCancelButtonActionPerformed
        
        if(processThread.isAlive())
        {
            try{
                processThread.stop();
                titleThread.stop();
                System.out.println("Threads successfully stopped.");
            }catch(Exception e){System.out.println("Thread stopping error: "+e);}
            this.setTitle("::. Update Merchant List");
            enableControls();
        }
        else
        dispose();
    }//GEN-LAST:event_jCancelButtonActionPerformed

private void jUpdateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jUpdateButtonActionPerformed

    if(jComboBox1.getSelectedItem().toString().equalsIgnoreCase("-- Select --")&&jCheckBox2.isSelected()==false)
    {
        JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),"Please Select A Profile ","ERROR !",JOptionPane.ERROR_MESSAGE);
        return;
    }
    int nAttrLst=0;
    for(int x=0;x<tableObject.length;x++)
    {
        if(jTable1.getValueAt(x, 1)!=null)
            if(jTable1.getValueAt(x, 1).equals(true))
                nAttrLst++;
    }
    if(nAttrLst==0&&jCheckBox2.isSelected()==false)
    {
        JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),"Please Select Profile's Merchant Name ","ERROR !",JOptionPane.ERROR_MESSAGE);
        return;
    }
    attributeList=new String[nAttrLst];int y=0;
    for(int x=0;x<tableObject.length;x++)
    {
        if(jTable1.getValueAt(x, 1)!=null)
            if(jTable1.getValueAt(x, 1).equals(true))
                attributeList[y++]=jTable1.getValueAt(x,0).toString().replace(' ', '_');
    }
    submitData();
    reset();
}//GEN-LAST:event_jUpdateButtonActionPerformed
void submitData()
{        
    if(jCheckBox2.isSelected())updateType=2;
    else if(jCheckBox1.isSelected())updateType=1;
    String query=systems.generateMerchantQuery(jComboBox1.getSelectedItem().toString().replace(' ', '_'),attributeList,updateType);
    //Connect.createMSSQLConnection();
    Connect.changeDB(OpenMSApp.Database_A);
        
    statement=Connect.createStatement("set global sql_mode='ANSI'"); 
    Connect.executeUpdateStatement(statement);
        
    statement=Connect.createStatement(Connect.procInit+" prnUpdMerchantSource"+Connect.procInitStart+"?"+Connect.procInitEnd);
    try
    {
        statement.setString(1,query);
    }
    catch(Exception e)
    {
        System.out.println("EditMerchantQuery.submitData() gave error ! "+e);
    }
    Connect.executeUpdateStatement(statement);
    systems.executeSplitedQuery(query.split(";"), statement);;
    Connect.alert="Y";
    Connect.closeConnection();
}
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
        
        /* Execute thread */
        processThread=new Thread(new Runnable() {
            public void run() {
                disableControls();
                profileCodeSelected();
            }
        });
        titleThread=new Thread(new Runnable() {
            public void run() {
                while(processThread.isAlive())setProcessingTitle(titleThread);
                enableControls();
                System.out.println("viewProfileThread stopped runing.");
            }
        });
        processThread.start();
        titleThread.start();
}//GEN-LAST:event_jComboBox1ActionPerformed
    private void disableControls()
    {
        jUpdateButton.setEnabled(false);
        jRefreshButton.setEnabled(false);
        jCheckBox1.setEnabled(false);
        jCheckBox2.setEnabled(false);
        jComboBox1.setEnabled(false);
    }                                             
    private void enableControls()
    {
        jUpdateButton.setEnabled(true);
        jRefreshButton.setEnabled(true);
        jCheckBox1.setEnabled(true);
        jCheckBox2.setEnabled(true);
        jComboBox1.setEnabled(true);
        this.setTitle("::. Update Merchant List");
    }
                   
    private void setProcessingTitle(Thread thread)
    {
        try{
            this.setTitle("::. Update Merchant List - Processing Request");
            thread.sleep(500);
            this.setTitle("::. Update Merchant List - Processing Request.");
            thread.sleep(500);
            this.setTitle("::. Update Merchant List - Processing Request..");
            thread.sleep(500);
            this.setTitle("::. Update Merchant List - Processing Request...");
            thread.sleep(500);
        }catch(Exception e){System.out.println("Title thread"+e);}
    }
    void print()
    {
        try
        {
            jTable1.print();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }    
    private void profileCodeSelected()
    {        
        String orderCode=jComboBox1.getSelectedItem().toString();
        if(orderCode.equals("-- Select --"))
        {
            reset();
        }
        else
        {
            refreshTable();
            setTitle("::. Update Merchant List");
        }
    }
    void reset()
    {
        resetProfileCode();
        resetTable();
        jCheckBox1.setSelected(false);
        jCheckBox2.setSelected(false);
    }
    void resetCombo()
    {
        resetProfileCode();
        resetTable();
    }
    void resetTable()
    {
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            tableObject,
            new String [] {
                "Profile Attribute", "Merchant Name"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, true
            };

            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Boolean.class
            };
            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        /* Execute thread */
        processThread=new Thread(new Runnable() {
            public void run() {
            disableControls();
            refreshTable();
            }
        });
        titleThread=new Thread(new Runnable() {
            public void run() {
                while(processThread.isAlive())setProcessingTitle(titleThread);
                enableControls();
                System.out.println("viewItemThread stopped runing.");
            }
        });
        processThread.start();
        titleThread.start();
    }
    void resetProfileCode()
    {
        String[] orderCode=systems.getTableDataArray(OpenMSApp.Database_A,"vwProfile",2);
        orderCode[0]="-- Select --";
        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(orderCode));
        setTitle("::. Update Merchant List");
    }
    void refreshTable()
    {      
        String refTableCode=systems.getValue(OpenMSApp.Database_A, "Select * from referencetable where vName='"+jComboBox1.getSelectedItem().toString()+"'", 1);
        String[] profileAttribute=systems.getTableDataArrayNum(OpenMSApp.Database_A,"Profile where cProfileCode='"+refTableCode+"' order by cProfileCode,iSerial",2);

        int x=0;
        int y=profileAttribute.length;

        tableObject=new Object[y][2];

        while(x<y)
        {
            tableObject[x][0]=profileAttribute[x].trim();
            tableObject[x][1]=false;
            x+=1;
            if(x==y){break;}
       }

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            tableObject,
            new String [] {
                "Profile Attribute", "Merchant Name"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, true
            };

            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Boolean.class
            };
            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });

    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jCancelButton;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JCheckBox jCheckBox2;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JButton jRefreshButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JButton jUpdateButton;
    // End of variables declaration//GEN-END:variables

}
